package controllers

import (
	"github.com/astaxie/beego"
	"io/ioutil"
	"os"
	"path"
	"strings"
)

type UeditorController struct {
	BaseController
}

// @router /ueditor/act [get,post]
func (u *UeditorController) Ue() {
	var res interface{}
	act := u.GetString("action")
	switch act {
	case "config": //获取配置
		res = u.getConfig()
		u.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
		u.Ctx.WriteString(res.(string))
		return
	case "uploadimage": //图片上传
		res = u.upload("upfile", "ueditor/image")
		break
	case "uploadfile": //文件，附件
		res = u.upload("upfile", "ueditor/file")
		break
	case "uploadvideo":
		res = u.upload("upfile", "ueditor/video")
		break
	case "uploadscrawl":
		res = u.rawl("upfile", "ueditor/scrawl")
		break
	}
	u.Data["json"] = res
	u.ServeJSON()
}

//获取配置信息
func (u *UeditorController) getConfig() interface{} {
	fp, _ := os.OpenFile(beego.AppConfig.String("ueditor_config"), os.O_RDONLY, 0755)
	defer fp.Close()
	all, _ := ioutil.ReadAll(fp)
	return string(all)
}

//上传
func (u *UeditorController) upload(field string, pathName string) interface{} {
	url := u.Ctx.Request.Host
	if strings.Contains(u.Ctx.Request.Proto, "HTTPS") {
		url = "https://" + url
	} else {
		url = "http://" + url
	}
	pre := make(map[string]interface{})
	res := u.BaseUpload(field, pathName)
	pre["url"] = url + res.Data.(string)
	pre["title"] = res.Data
	if res.Code == 1 {
		pre["state"] = "SUCCESS"
	} else {
		pre["state"] = res.Msg
	}
	_, h, err := u.GetFile(field)
	if err != nil {
		pre["state"] = err.Error()
	}
	pre["original"] = h.Filename
	pre["size"] = res.Count
	pre["type"] = path.Ext(h.Filename)
	return pre
}

//base64
func (u *UeditorController) rawl(field string, pathName string) interface{} {
	url := u.Ctx.Request.Host
	if strings.Contains(u.Ctx.Request.Proto, "HTTPS") {
		url = "https://" + url
	} else {
		url = "http://" + url
	}
	pre := make(map[string]interface{})
	res, ext := u.Base64ToFile(u.GetString(field), pathName, ".png")
	pre["url"] = url + res.Data.(string)
	pre["title"] = res.Data
	if res.Code == 1 {
		pre["state"] = "SUCCESS"
	} else {
		pre["state"] = res.Msg
	}
	pre["original"] = pre["title"]
	pre["size"] = res.Count
	pre["type"] = ext
	return pre
}
